package org.cyhz.main;

import java.io.File;
import java.sql.SQLException;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.cyhz.utils.Log;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * @Title: MainEntrance.java
 * @Package org.cyhz.main
 * @author Corleone
 * @date 2013年11月18日 下午2:18:37
 * @version V1.0
 */
public class MainEntrance {

    public static void main(String[] args) throws SQLException {
        start(args);
    }

    @SuppressWarnings("resource")
    private static void start(String[] args) {
        overrideCommandLineProperty(args);
        Log.info("start discarding queue ....................");

        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        ConfigService config = ac.getBean(ConfigService.class);

        String p = config.getImportFile();
        File file=new File(".");
        System.out.println(file.getAbsolutePath());
        
        if (new File(config.getImportFile()).exists()) {
            @SuppressWarnings("unused")
            FileSystemXmlApplicationContext ac2 = new FileSystemXmlApplicationContext(
                    p);
        } else {
            Log.error("config file not exist:" + config.getImportFile());
        }

    }

    private static final void overrideCommandLineProperty(String[] args) {
        Options os = new Options();
        // 此处定义参数类似于 java 命令中的 -D<name>=<value>
        OptionBuilder.hasArgs(2);
        OptionBuilder.withArgName("property=value");
        OptionBuilder.hasArgs(2);
        OptionBuilder.withValueSeparator();
        OptionBuilder
                .withDescription("search the objects which have the target property and value");
        OptionBuilder.create("D");
        CommandLineParser clp = new GnuParser();
        Properties sysp = System.getProperties();
        try {
            CommandLine cmd = clp.parse(os, args);
            Properties p = cmd.getOptionProperties("D");
            for (Entry<Object, Object> ok : p.entrySet()) {
                String key = String.valueOf(ok.getKey());
                String value = String.valueOf(ok.getValue());
                if (sysp.containsKey(key)) {
                    throw new RuntimeException(
                            "property config exist in system property:" + key);
                } else {
                    sysp.put(key, value);
                    Log.info("put property:" + key + "=" + value);
                }
            }
        } catch (ParseException e) {
            Log.error("", e);
        }
    }
}